package main

import (
	"context"
	"fmt"

	"gitee.com/fu-ce-wei/pi-mapper/internal/config"
	"gitee.com/fu-ce-wei/pi-mapper/internal/service"
	"gitee.com/fu-ce-wei/pi-mapper/pkg/logger"
	"gitee.com/fu-ce-wei/pi-mapper/pkg/redis"
	"go.uber.org/zap"
)

// loadConfiguration 加载配置文件
func loadConfiguration() (*config.Config, error) {
	cfg, err := config.LoadConfig(*configFile)
	if err != nil {
		return nil, fmt.Errorf("加载配置文件失败: %v", err)
	}
	return cfg, nil
}

// setupLogger 初始化日志系统
func setupLogger(cfg *config.Config) (*logger.Logger, error) {
	logConfig := logger.Config{
		Level:      cfg.Log.Level,
		Output:     cfg.Log.Output,
		MaxSize:    cfg.Log.MaxSize,
		MaxBackups: cfg.Log.MaxBackups,
		MaxAge:     cfg.Log.MaxAge,
	}

	appLogger, err := logger.NewLogger(logConfig)
	if err != nil {
		return nil, fmt.Errorf("初始化日志失败: %v", err)
	}

	return appLogger, nil
}

// setupRedis 初始化Redis客户端
func setupRedis(cfg *config.Config, appLogger *logger.Logger) *redis.Client {
	redisClient := redis.NewClient(
		cfg.GetRedisAddr(),
		cfg.Redis.Password,
		cfg.Redis.DB,
		cfg.Redis.PoolSize,
	)

	// 检查Redis连接
	if err := redisClient.Ping(context.Background()); err != nil {
		appLogger.Fatal("Redis连接失败", zap.Error(err))
	}
	appLogger.Info("Redis连接成功")

	return redisClient
}

// Services 服务集合结构体
type Services struct {
	VideoService     service.VideoService
	ScanService      service.ScanService
	ImageService     service.ImageService
	ImageScanService service.ImageScanService
}

// setupServices 初始化所有服务
func setupServices(redisClient *redis.Client, cfg *config.Config, appLogger *logger.Logger) *Services {
	return &Services{
		VideoService:     service.NewVideoService(redisClient, cfg, appLogger),
		ScanService:      service.NewScanService(redisClient, cfg, appLogger),
		ImageService:     service.NewImageService(redisClient, cfg, appLogger),
		ImageScanService: service.NewImageScanService(redisClient, cfg, appLogger),
	}
}

// printVersionInfo 打印版本信息
func printVersionInfo() {
	fmt.Printf("PiMapper %s (build: %s, commit: %s)\n", version, buildTime, gitCommit)
}
